import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Input,
  Button,
  Form,
  DatePicker,
  InputNumber,
  message,
  TreeSelect
} from 'antd';
import Drawer from 'react-motion-drawer';
import PSelect from "../../../components/Pro/PSelect";
import './less/devices.less';
import * as api from "../../../services/api";

import PartmentButton from "../../../components/PartmentButton";

const FormItem = Form.Item;
const { TextArea } = Input;

@connect(state => ({ profile: state.profile }))
@Form.create()



export default class CheckInOutDrawer extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      lostState: 'no',
      open: this.props.visible,//出入库
      comEquipId: 0,
      comEquipList: {
        equipNo: '',//设备编号
        equipName: '',//设备名称
        equipType: '',//设备类型
        totalNum: '',//总库存
        curNum: '',//当前库存
      },
      treeData:[],
      userIdArrays:[],//表单显示用的人员id集合
      addDepartmentUserVisible: false,
      perId:'',//人员id
      checkedkeys: "",
    };
  }
  onChangeRadio = (e) => {
    console.log(e.target.value);
    this.setState({ lostState: e.target.value });
  };
  componentWillReceiveProps(props) {
    this.setState({ open: props.visible });
    this.setState({
      comEquipId: props.comEquipId,
    }, () => {
      if (this.state.comEquipId !== 0) {
        api.enterpriseEquipComEquipGetComEquipById({ comEquipId: (props.comEquipId) }).then((data) => {
          console.log('获取企业设备详情', data.data);
          this.setState({
            comEquipList: data.data,
          });
        });
      }
    });
    api.getTreeperBydepart({}).then((data)=>{
      this.setState({treeData : data.data});
      console.log('部门信息', data.data);
    });
  }

  //表单提交
  handleAddDeviceSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // values.perIdStr=values.perIdStr[0];
        values.perIdStr = this.state.perId;
        console.log('Received values of form: ', values);
        values.operaDate = values['operaDate'].format('YYYY-MM-DD HH:mm');
        console.log(values.operaDate, "!!!!!!!!!!!!!!");
        values.comEquipId = this.state.comEquipId;
        delete values.storage;
        delete values.equipName;
        delete values.equipNo;
        delete values.equipType;
        delete values.perId;
        api.comEquipInOutAddComEquipInOut({ ...values }).then(() => {
          message.success('提交成功');
          this.setState({
            open: false,
            userIdArrays:[]
          });
        }, (err1) => {
          console.log(err1);
        });
      }
    });
  };

  //保证数量小于实际库存
  checkNumber = (rule, value, callback) => {
    const stockType = this.props.form.getFieldValue('inOutStockType');
    const curNum = this.state.comEquipList.curNum;
    const totalNum = this.state.comEquipList.totalNum;
    const outNum = totalNum - curNum;
    if (stockType === undefined) {
      callback('请先选择出入库类型！');
    } else if (stockType === '2' && (value > outNum)) {
      callback('设备入库数量不能大于实际出库数量！');
    } else if ((stockType === '1') && (value > curNum)) {
      callback('设备出库数量不能大于实际库存数量！');
    } else if ((stockType === '4') && (value > totalNum)) {
      callback('设备损耗数量不能大于库存总数量！');
    } else if (value && !(/^[1-9]\d*$/).test(value)) {
      callback('输入格式不正确！');
    } else {
      callback();
    }
  };


  //抽屉视图处理
  changeDrawer = () => {
    this.setState({ open: true });
  };

  //树选中事件
  treeSelectOnChangeHandler = (value,label,extra) =>{
    console.log('选中的值',value,label,extra);
    this.setState({ userIdArrays:value });
  };

  render() {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 17
        },
        md: {
          span: 17
        }
      }
    };

    const { getFieldDecorator,setFieldsValue } = this.props.form;
    const lostView = (this.state.lostState === "no")
      ? (
        <FormItem {...formItemLayout} label="数量">{getFieldDecorator('operaNum', {
          rules: [
            {
              required: true, message: '数量不能为空！'
            }, {
              validator: this.checkNumber
            }
          ]
        })(<InputNumber style={{ width: 294 }} min={1} max={100000} />)}
        </FormItem>
      )
      : (
        <div>
          <FormItem {...formItemLayout} label="实际入库数量">
            {getFieldDecorator('storageNumber', {
              rules: [
                {
                  required: false
                }
              ]
            })(<InputNumber style={{ width: 294 }} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="损耗设备数量">
            {getFieldDecorator('loseNumber', {
              rules: [
                {
                  required: false
                }
              ]
            })(<InputNumber />)}
          </FormItem>
          <FormItem {...formItemLayout} label="耗损说明">
            {getFieldDecorator('loseRemark')(<TextArea style={{ width: 294 }} rows={4} />)}
          </FormItem>
        </div>
      );
    const config = {
      rules: [
        {
          type: 'object',
          required: true,
          message: '请选择日期!'
        }
      ]
    };
    return (
      <Drawer
        overlayColor="rgba(0, 0, 0,0)"
        right
        open={this.state.open}
        noTouchClose
        zIndex={2}
        width={600}
        className="drawer-box"
        onChange={(open) => {
          this.props.onChange(open);
          this.setState({ open });
          if(open === false){
            const form = this.props.form;
            form.setFieldsValue({perId:'',inOutStockType:'',operaNum:'',storageNumber:'',loseNumber:'',loseRemark:'',remark:''});
            if(form.getFieldValue('operaDate')){
              form.setFieldsValue({operaDate:null});
            }
          }
        }}
      >
        <div className="drawer">
          <div className="drawer-header">
            出库入库
            </div>
          <div className="drawer-content">
            <Form onSubmit={this.handleAddDeviceSubmit}>
              <FormItem
                {...formItemLayout}
                label="设备编号"
              >
                {getFieldDecorator('equipNo', {
                  initialValue: this.state.comEquipList.equipNo
                })(
                  <Input style={{ width: 294 }} disabled />
                  )}
              </FormItem>
              <FormItem {...formItemLayout} label="设备名称:">
                {getFieldDecorator('equipName',
                  {
                    initialValue: this.state.comEquipList.equipName
                  })(<Input style={{ width: 294 }} disabled />)}
              </FormItem>
              <FormItem {...formItemLayout} label="设备类型">
                {getFieldDecorator('equipType',
                  { initialValue: this.state.comEquipList.equipType }
                )(<PSelect style={{ width: 294 }} placeholder="请选择" type="equipType" onChange={this.pSelectChange} disabled />)}
              </FormItem>
              <FormItem {...formItemLayout} label="出入库类型">
                {getFieldDecorator('inOutStockType', {
                  rules: [
                    {
                      required: true, message: '请选择出入库类型'
                    }
                  ]
                })(
                  <PSelect style={{ width: 294 }} type="inOutStockType" onChange={this.pSelectChange} onSelect={
                    () => {
                      this.props.form.setFieldsValue({ 'operaNum': '' });
                    }
                  } />
                  )}
              </FormItem>
              {/*<FormItem {...formItemLayout} label="是否有设备耗损">*/}
              {/*{getFieldDecorator('loseState')(*/}
              {/*<RadioGroup style={{width:294}} onChange={this.onChangeRadio}>*/}
              {/*<Radio value={'no'}>否</Radio>*/}
              {/*/!*<Radio style={{marginLeft:94}} value={'yes'}>是</Radio>*!/*/}
              {/*</RadioGroup>*/}
              {/*)}*/}
              {/*</FormItem>*/}
              {lostView}
              <FormItem {...formItemLayout} label="实际库存">
                {getFieldDecorator('storage')(
                  <p>
                    <span style={{ color: 'red' }}>{this.state.comEquipList.curNum}</span><span style={{ color: '#333' }}>/{this.state.comEquipList.totalNum}</span>
                  </p>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="负责人">
                {getFieldDecorator('perId')(
                  //{/*<TreeSelect {...tProps}/>*/}
                  <Input
                    style={{width:'292px'}}
                  onClick={() => {
                  this.setState({ addDepartmentUserVisible: true });
                }}
                  placeholder="请选择"
                  />
                )}
              </FormItem>

              <PartmentButton
                handleCancel={() => {
                  this.setState({ addDepartmentUserVisible: false });
                }}
                onCheck={(checkedkeys, selectUser) => {
                  console.log(
                    checkedkeys,
                    selectUser,
                    "checkedkeys-selectUser"
                  );
                  const user = selectUser[0];
                  this.setState({
                    perId: selectUser.length > 0 ? user.key : "",
                    addDepartmentUserVisible: false,
                    checkedkeys
                  });
                  setFieldsValue({
                    perId: selectUser.length > 0 ? user.title : ""
                  });
                }}
                value={this.state.checkedkeys}
                visible={this.state.addDepartmentUserVisible}
                type="radio"
              />

              <FormItem {...formItemLayout} label="操作日期">
                {getFieldDecorator('operaDate', config)(<DatePicker format="YYYY-MM-DD HH:mm"
                  showTime={{ format: 'HH:mm' }}
                  style={{ width: 294 }} />)}
              </FormItem>
              <FormItem {...formItemLayout} label="备注">
                {getFieldDecorator('remark', {
                  initialValue: ""
                })(<TextArea style={{ width: 294 }} maxLength="400" rows={4} />)}
              </FormItem>
            </Form>
          </div>
          <div className="drawer-footer">
            <Button onClick={() => {

              this.setState({ open: false });
            }}>取消</Button>
            <Button type="primary" htmlType="submit" onClick={this.handleAddDeviceSubmit}>确定</Button>
          </div>
        </div>
      </Drawer>
    );
  }
}
